package com.haojiang.mh.ui.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.recyclerview.widget.RecyclerView;
import com.clj.fastble.data.BleDevice;
import com.haojiang.mh.R;

import java.util.List;

/**
 * 设备列表
 * <p>
 * Created by ZapFive on 2019-05-26.
 * <p>
 * wuzhuang@mirahome.me
 */
public class BtDeviceListAdapter extends RecyclerView.Adapter<BtDeviceListAdapter.MyHolder> {

    private List<BleDevice> dataList;
    private OnItemChildClickListener itemClickListener;
    private Context ctx;

    public BtDeviceListAdapter(Context ctx, List<BleDevice> dataList) {
        this.ctx = ctx;
        this.dataList = dataList;
    }

    public void setItemClickListener(OnItemChildClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(ctx).inflate(R.layout.item_pillow_device, parent, false);
        return new MyHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull final MyHolder holder, final int position) {
        BleDevice device = dataList.get(position);
        holder.tv_device_id.setText(String.format("%s %s", device.getName(), device.getMac()));
        holder.aiv_connect.setOnClickListener(v -> {
            if (itemClickListener != null) {
                int adapterPosition = holder.getAdapterPosition();
                itemClickListener.onItemClick(v, dataList.get(adapterPosition), adapterPosition);
            }
        });
    }

    @Override
    public int getItemCount() {
        if (dataList == null) {
            return 0;
        } else {
            return dataList.size();
        }
    }

    class MyHolder extends RecyclerView.ViewHolder {

        TextView tv_device_id;
        AppCompatImageView aiv_connect;

        public MyHolder(@NonNull View itemView) {
            super(itemView);
            tv_device_id = itemView.findViewById(R.id.tv_device_id);
            aiv_connect = itemView.findViewById(R.id.aiv_connect);
        }
    }
}
